﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;

namespace Solution
{
    public class Logger
    {
        #region 构造

        static Logger()
        {
            _logger = new FileLogger();
        }

        #endregion 构造

        #region 字段

        private static readonly FileLogger _logger;

        #endregion 字段

        #region 公共方法

        public static void Error(string group, Exception exception, FileLogger.LogType logType = FileLogger.LogType.Daily)
        {
            //var message = $"\r\n\r\n============================================================\r\n\r\n[Error Text]{exception.Message}\r\n[Error Full]{exception}";

            StringBuilder sb = new StringBuilder();
            sb.AppendLine("时间：" + DateTime.Now);
            if (HttpContext.Current != null)
            {
                sb.AppendLine("【Url】：" + HttpContext.Current.Request.Url.OriginalString);
                sb.AppendLine("【IP】:" + HttpContext.Current.Request.UserHostAddress);
                sb.AppendLine("【Agent】:" + HttpContext.Current.Request.UserAgent);
            }

            sb.AppendLine("异常IP：" + HttpContext.Current.Request.UserHostAddress);
            sb.AppendLine("异常消息：" + exception.Message);
            sb.AppendLine("异常类型：" + exception.GetType().FullName);
            sb.AppendLine("异常方法：" + (exception.TargetSite == null ? null : exception.TargetSite.Name));
            sb.AppendLine("异常源：" + exception.Source);

            // sb.AppendLine("============================================================");

            _logger.Log(group, sb.ToString(), logType);
        }

        public static void Error(string group, string message, FileLogger.LogType logType = FileLogger.LogType.Daily)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("时间：" + DateTime.Now);
            if (HttpContext.Current != null)
            {
                sb.AppendLine("【Url】：" + HttpContext.Current.Request.Url.OriginalString);
                sb.AppendLine("【IP】:" + HttpContext.Current.Request.UserHostAddress);
                sb.AppendLine("【Agent】:" + HttpContext.Current.Request.UserAgent);
            }
            sb.AppendLine("详情：" + message);
            // sb.AppendLine("============================================================");

            _logger.Log(group, sb.ToString(), logType);
        }

        public static Dictionary<string, string> GetLogs()
        {
            return _logger.GetLogs();
        }

        #endregion 公共方法
    }
}